// pages/like/like.js
const app = getApp()

Page({
  data: {
    currentTab: 0, // 0: 喜欢我的, 1: 最近来访
    likedMeUsers: [],
    visitedUsers: [],
    isLoading: true
  },

  onLoad() {
    this.checkAuthAndLoadData();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.loadData();
    }
  },

  // 检查授权并加载数据
  checkAuthAndLoadData() {
    if (app.globalData.userInfo) {
      this.loadData();
    } else {
      wx.redirectTo({
        url: '/pages/login/login'
      });
    }
  },

  // 切换选项卡
  switchTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    this.setData({
      currentTab: tab
    });
  },

  // 加载数据
  loadData() {
    this.setData({ isLoading: true });

    // 使用模拟数据
    if (app.globalData.useMockData) {
      setTimeout(() => {
        const mockLikedMeUsers = [
          {
            id: '2001',
            nickname: '温柔小姐姐',
            age: 23,
            gender: 'female',
            city: '北京',
            school: '清华大学',
            verified: true,
            avatar_url: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=400&h=400&fit=crop&crop=face',
            introduction: '性格温柔，喜欢安静的生活，期待遇见真诚的你。',
            tags: ['阅读', '音乐', '瑜伽', '烹饪'],
            liked_time: '2小时前',
            is_matched: false
          },
          {
            id: '2002',
            nickname: '运动达人',
            age: 27,
            gender: 'male',
            city: '上海',
            school: '上海交通大学',
            verified: true,
            avatar_url: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=400&fit=crop&crop=face',
            introduction: '热爱各种运动，性格开朗，希望找到一起运动的伙伴。',
            tags: ['篮球', '跑步', '游泳', '健身'],
            liked_time: '昨天',
            is_matched: true
          },
          {
            id: '2003',
            nickname: '文艺女孩',
            age: 24,
            gender: 'female',
            city: '杭州',
            school: '中国美术学院',
            verified: false,
            avatar_url: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=400&h=400&fit=crop&crop=face',
            introduction: '喜欢艺术和设计，热爱生活中的美好事物。',
            tags: ['绘画', '设计', '摄影', '旅行'],
            liked_time: '3天前',
            is_matched: false
          }
        ];

        const mockVisitedUsers = [
          {
            id: '3001',
            nickname: '阳光男孩',
            age: 26,
            gender: 'male',
            city: '深圳',
            school: '深圳大学',
            verified: true,
            avatar_url: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&h=400&fit=crop&crop=face',
            introduction: '热爱生活，喜欢户外运动，性格开朗乐观。',
            tags: ['跑步', '健身', '游泳', '爬山'],
            visit_time: '1小时前'
          },
          {
            id: '3002',
            nickname: '知性女生',
            age: 25,
            gender: 'female',
            city: '广州',
            school: '中山大学',
            verified: true,
            avatar_url: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?w=400&h=400&fit=crop&crop=face',
            introduction: '喜欢读书和思考，追求精神世界的丰富。',
            tags: ['阅读', '写作', '哲学', '心理学'],
            visit_time: '3小时前'
          },
          {
            id: '3003',
            nickname: '音乐才子',
            age: 28,
            gender: 'male',
            city: '成都',
            school: '四川音乐学院',
            verified: false,
            avatar_url: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=400&h=400&fit=crop&crop=face',
            introduction: '热爱音乐创作，擅长多种乐器，性格温和。',
            tags: ['音乐', '吉他', '钢琴', '创作'],
            visit_time: '昨天'
          }
        ];

        this.setData({
          likedMeUsers: mockLikedMeUsers,
          visitedUsers: mockVisitedUsers,
          isLoading: false
        });
      }, 1000);
      return;
    }

    // 实际API调用逻辑
    this.loadDataFromAPI();
  },

  // 从API加载数据
  async loadDataFromAPI() {
    try {
      // 加载喜欢我的用户
      const likedMeResult = await wx.request({
        url: `${app.globalData.baseUrl}/matches/liked_me`,
        method: 'GET',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        }
      });

      // 加载最近来访用户
      const visitedResult = await wx.request({
        url: `${app.globalData.baseUrl}/matches/visited`,
        method: 'GET',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        }
      });

      if (likedMeResult.data.success && visitedResult.data.success) {
        this.setData({
          likedMeUsers: likedMeResult.data.data.users || [],
          visitedUsers: visitedResult.data.data.users || [],
          isLoading: false
        });
      } else {
        app.showError('加载失败');
        this.setData({ isLoading: false });
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      app.showError('网络错误，请重试');
      this.setData({ isLoading: false });
    }
  },

  // 我也喜欢（回应喜欢我的用户）
  likeUserBack(e) {
    const userId = e.currentTarget.dataset.userId;
    
    wx.showModal({
      title: '确认喜欢',
      content: '确定要喜欢这个用户吗？',
      success: (res) => {
        if (res.confirm) {
          this.likeUserBackAPI(userId);
        }
      }
    });
  },

  // API我也喜欢
  async likeUserBackAPI(userId) {
    try {
      const result = await wx.request({
        url: `${app.globalData.baseUrl}/matches/like_back`,
        method: 'POST',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        },
        data: { target_user_id: userId }
      });

      if (result.data.success) {
        app.showSuccess('喜欢成功，已匹配');
        // 更新用户状态为已匹配
        const users = this.data.likedMeUsers.map(user => {
          if (user.id === userId) {
            return { ...user, is_matched: true };
          }
          return user;
        });
        this.setData({ likedMeUsers: users });
      } else {
        app.showError(result.data.message || '操作失败');
      }
    } catch (error) {
      console.error('喜欢失败:', error);
      app.showError('操作失败');
    }
  },

  // 喜欢用户（最近来访页面）
  likeUser(e) {
    const userId = e.currentTarget.dataset.userId;
    
    wx.showModal({
      title: '确认喜欢',
      content: '确定要喜欢这个用户吗？',
      success: (res) => {
        if (res.confirm) {
          this.likeUserAPI(userId);
        }
      }
    });
  },

  // API喜欢用户
  async likeUserAPI(userId) {
    try {
      const result = await wx.request({
        url: `${app.globalData.baseUrl}/matches/like`,
        method: 'POST',
        header: {
          Authorization: `Bearer ${app.globalData.token}`
        },
        data: { target_user_id: userId }
      });

      if (result.data.success) {
        app.showSuccess('喜欢成功');
        // 从最近来访列表中移除用户
        const users = this.data.visitedUsers.filter(user => user.id !== userId);
        this.setData({ visitedUsers: users });
      } else {
        app.showError(result.data.message || '操作失败');
      }
    } catch (error) {
      console.error('喜欢失败:', error);
      app.showError('操作失败');
    }
  },

  // 开始聊天
  startChat(e) {
    const userId = e.currentTarget.dataset.userId;
    let user;
    
    // 根据当前选项卡查找用户
    if (this.data.currentTab === 0) {
      user = this.data.likedMeUsers.find(user => user.id === userId);
    } else {
      user = this.data.visitedUsers.find(user => user.id === userId);
    }
    
    if (user && user.is_matched) {
      wx.navigateTo({
        url: `/pages/chat/chat?targetUserId=${userId}`
      });
    } else {
      wx.showToast({
        title: '对方还未喜欢您，无法聊天',
        icon: 'none'
      });
    }
  },

  // 查看用户详情
  viewUserDetail(e) {
    const userId = e.currentTarget.dataset.userId;
    let user;
    
    // 根据当前选项卡查找用户
    if (this.data.currentTab === 0) {
      user = this.data.likedMeUsers.find(user => user.id === userId);
    } else {
      user = this.data.visitedUsers.find(user => user.id === userId);
    }
    
    if (user) {
      wx.showModal({
        title: user.nickname,
        content: `${user.age}岁 · ${user.city}\n${user.introduction || '这个人很懒，还没有写简介'}`,
        showCancel: false
      });
    }
  },

  // 去发现页面
  goToExplore() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  }
})
